package ceha.application;

import ceha.application.archivage.ArchivageFrame;
import ceha.application.consultation.ConsultationFrame;
import ceha.util.Mysql;
import ceha.util.SystemTrayCde;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.Beans;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class CEHA extends javax.swing.JFrame {

    private boolean login;
    private boolean loginadmin;
    private Mysql mysql;
    private AdministrationFrame adminparam;
    private Connection conn;
    private JFrame commandescreateJFrame;
    private JFrame recherchesconsultJFrame;
    private ConsultationFrame consultJFrame;
    private ArchivageFrame archivageJFrame;
    private int archivageOpen;
    private int commandescreateOpen;
    private int rechercheconsult;
    private String initialeLogin;


    public CEHA() throws IOException {

        new SystemTrayCde(this);
        adminparam = new AdministrationFrame();
        mysql = new Mysql(this);
        mysql.setUrl(adminparam.getUrlF().getText());
        mysql.setDriver(adminparam.getDriverF().getText());
        mysql.setPassword(adminparam.getPasswordF().getText());
        mysql.setUserName(adminparam.getUsernameF().getText());
        mysql.setDbName(adminparam.getDatabasenameF().getText());
//        conn = mysql.Connect();
        initComponents();
        setLocation(10, 10);
        initialiser();
    }

    public String getInitialeLogin() {
        return initialeLogin;
    }

    public JTextField getPseudoField() {
        return pseudoField;
    }

    public boolean isLoginadmin() {
        return loginadmin;
    }

    public JFrame getRecherchesconsultJFrame() {
        return recherchesconsultJFrame;
    }

    public JFrame getCommandescreateJFrame() {
        return commandescreateJFrame;
    }

    public Connection getConn() {
        return conn;
    }

    public AdministrationFrame getAdminparam() {
        return adminparam;
    }

    public String getRepVignette() {
        return adminparam.getRepvignette().getText();
    }

    public boolean is17pouces() {
        return adminparam.isEcr17p();
    }

    public String getMysqlF() {
        return adminparam.getMysqlF().getText();
    }

    private void initialiser() throws IOException {

        try {
            UIManager.setLookAndFeel("WindowsLookAndFeel");
        } catch (InstantiationException e) {
        } catch (ClassNotFoundException e) {
        } catch (UnsupportedLookAndFeelException e) {
        } catch (IllegalAccessException e) {
        }
        if (adminparam.getCheckAuto().isEnabled()) {
            pseudoField.setText(adminparam.getPseudoAuto().getText());
            passField.setText(adminparam.getPassAuto().getText());
        }
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        adminButton.setEnabled(false);
        creerficheButton.setEnabled(false);
        mainpanel.setVisible(true);
        loginPanel.setVisible(true);
        logoutButton.setEnabled(false);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("BDDCEHAPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT f FROM Fiche f");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        mainpanel = new javax.swing.JPanel();
        panelB = new javax.swing.JPanel();
        consultButton = new javax.swing.JButton();
        loginPanel = new javax.swing.JPanel();
        pseudoLabel = new javax.swing.JLabel();
        pseudoField = new javax.swing.JTextField();
        passLabel = new javax.swing.JLabel();
        passField = new javax.swing.JPasswordField();
        loginButton = new javax.swing.JButton();
        creerficheButton = new javax.swing.JButton();
        adminButton = new javax.swing.JButton();
        logoutButton = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        fichierM = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("BASE DE DONNEES  DU  CEHA");
        setBackground(new java.awt.Color(0, 0, 0));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        mainpanel.setBackground(new java.awt.Color(0, 0, 0));
        mainpanel.setPreferredSize(new java.awt.Dimension(400, 178));
        mainpanel.setLayout(new java.awt.GridLayout(2, 3));

        panelB.setBackground(new java.awt.Color(0, 0, 0));
        panelB.setPreferredSize(new java.awt.Dimension(400, 85));

        consultButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ceha/ressource/fiches.gif"))); // NOI18N
        consultButton.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 255, 255), 2, true), "Consultation", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Trebuchet MS", 1, 14), new java.awt.Color(255, 255, 255))); // NOI18N
        consultButton.setContentAreaFilled(false);
        consultButton.setFocusable(false);
        consultButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        consultButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                consultA(evt);
            }
        });

        javax.swing.GroupLayout panelBLayout = new javax.swing.GroupLayout(panelB);
        panelB.setLayout(panelBLayout);
        panelBLayout.setHorizontalGroup(
            panelBLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(consultButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE)
        );
        panelBLayout.setVerticalGroup(
            panelBLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBLayout.createSequentialGroup()
                .addComponent(consultButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        mainpanel.add(panelB);

        loginPanel.setBackground(new java.awt.Color(153, 153, 153));
        loginPanel.setPreferredSize(new java.awt.Dimension(200, 46));
        loginPanel.setLayout(new java.awt.GridLayout(2, 2));

        pseudoLabel.setBackground(new java.awt.Color(204, 204, 204));
        pseudoLabel.setFont(new java.awt.Font("Times New Roman", 1, 12));
        pseudoLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pseudoLabel.setText("Pseudo ");
        pseudoLabel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        pseudoLabel.setOpaque(true);
        loginPanel.add(pseudoLabel);

        pseudoField.setBackground(new java.awt.Color(255, 255, 204));
        pseudoField.setFont(new java.awt.Font("Arial", 1, 12));
        pseudoField.setToolTipText("");
        pseudoField.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED, new java.awt.Color(51, 102, 255), new java.awt.Color(204, 255, 255), null, null));
        loginPanel.add(pseudoField);

        passLabel.setBackground(new java.awt.Color(204, 204, 204));
        passLabel.setFont(new java.awt.Font("Times New Roman", 1, 12));
        passLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        passLabel.setText("Mot de passe");
        passLabel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        passLabel.setOpaque(true);
        loginPanel.add(passLabel);

        passField.setBackground(new java.awt.Color(255, 255, 204));
        passField.setFont(new java.awt.Font("Arial", 1, 12));
        passField.setToolTipText("laissez les champs vides pour une simple recherche");
        passField.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED, new java.awt.Color(51, 51, 255), new java.awt.Color(204, 255, 255), null, null));
        loginPanel.add(passField);

        mainpanel.add(loginPanel);

        loginButton.setBackground(new java.awt.Color(255, 255, 204));
        loginButton.setFont(new java.awt.Font("Times New Roman", 1, 14));
        loginButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ceha/ressource/Login.png"))); // NOI18N
        loginButton.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(51, 204, 0), 2, true), "Entrer", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Trebuchet MS", 1, 14), new java.awt.Color(0, 255, 0))); // NOI18N
        loginButton.setContentAreaFilled(false);
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginA(evt);
            }
        });
        mainpanel.add(loginButton);

        creerficheButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ceha/ressource/fiche.jpg"))); // NOI18N
        creerficheButton.setToolTipText("");
        creerficheButton.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 255, 204), 2, true), "Archivage", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Trebuchet MS", 1, 14), new java.awt.Color(255, 255, 255))); // NOI18N
        creerficheButton.setContentAreaFilled(false);
        creerficheButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                creerficheA(evt);
            }
        });
        mainpanel.add(creerficheButton);

        adminButton.setFont(new java.awt.Font("Trebuchet MS", 0, 18));
        adminButton.setForeground(new java.awt.Color(255, 255, 255));
        adminButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ceha/ressource/administration.gif"))); // NOI18N
        adminButton.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 0, 0), 2, true), "Administration", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Trebuchet MS", 1, 14), new java.awt.Color(255, 255, 255))); // NOI18N
        adminButton.setContentAreaFilled(false);
        adminButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                adminA(evt);
            }
        });
        mainpanel.add(adminButton);

        logoutButton.setBackground(new java.awt.Color(255, 255, 255));
        logoutButton.setFont(new java.awt.Font("Times New Roman", 1, 12));
        logoutButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ceha/ressource/48px-System-log-out-2.svg.png"))); // NOI18N
        logoutButton.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 2, true), "Sortir", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Trebuchet MS", 1, 14), new java.awt.Color(255, 255, 255))); // NOI18N
        logoutButton.setContentAreaFilled(false);
        logoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutA(evt);
            }
        });
        mainpanel.add(logoutButton);

        fichierM.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        fichierM.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ceha/ressource/petitlogoCEHA.jpg"))); // NOI18N
        fichierM.setText("Menu");
        fichierM.setContentAreaFilled(false);
        fichierM.setFont(new java.awt.Font("Trebuchet MS", 1, 12));

        jMenuItem1.setFont(new java.awt.Font("Trebuchet MS", 3, 12));
        jMenuItem1.setText("Quitter");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quitterAction(evt);
            }
        });
        fichierM.add(jMenuItem1);

        jMenuBar1.add(fichierM);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(mainpanel, javax.swing.GroupLayout.PREFERRED_SIZE, 431, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(mainpanel, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void consultA(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_consultA
        if (rechercheconsult != 1) {
            consultJFrame = new ConsultationFrame(this);
            consultJFrame.setVisible(true);
            consultJFrame.setLocation(10, 180);
//        JFrame frame = new JFrame("Recherches");
//        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//        JPanel panel = consult.getRecherches();
//        frame.getContentPane().add(panel, BorderLayout.CENTER);
//        frame.setLocation(700, 180);
//        frame.setVisible(true);
//        frame.pack();

            recherchesconsultJFrame = new JFrame("Recherches");
            recherchesconsultJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            JPanel panelMasterTable = consultJFrame.getTablePanel();
            recherchesconsultJFrame.getContentPane().add(panelMasterTable, BorderLayout.CENTER);
            final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(consultJFrame.getMasterTable().getModel());
            consultJFrame.getMasterTable().setRowSorter(sorter);
            consultJFrame.getFiltrerB().addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    String text = consultJFrame.getFiltrerF().getText();
                    if (text.length() == 0) {
                        sorter.setRowFilter(null);
                    } else {
                        sorter.setRowFilter(RowFilter.regexFilter(text));
                    }
                }
            });
            recherchesconsultJFrame.setLocation(700, 180);
            recherchesconsultJFrame.setVisible(true);
            recherchesconsultJFrame.pack();
            rechercheconsult++;
        }

    }//GEN-LAST:event_consultA

    private void adminA(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adminA
        if (loginadmin) {
            adminButton.setEnabled(true);
            adminparam.setVisible(login);
        }
}//GEN-LAST:event_adminA

    private void creerficheA(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_creerficheA
        if ((commandescreateOpen != 1) && (archivageOpen != 1)) {
            consultButton.setEnabled(false);
            //
            archivageJFrame = new ArchivageFrame(this);
            archivageJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            archivageJFrame.getCommandes().setVisible(false);
            archivageJFrame.setLocation(10, 180);
            archivageJFrame.setVisible(true);

            commandescreateJFrame = new JFrame("Commandes");
            commandescreateJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            JPanel panel = archivageJFrame.getCommandes();
            panel.setVisible(true);
            commandescreateJFrame.getContentPane().add(panel, BorderLayout.CENTER);
            commandescreateJFrame.setLocation(820, 180);
            commandescreateJFrame.setVisible(true);
            commandescreateJFrame.pack();
            archivageOpen++;
            commandescreateOpen++;
        }
    }//GEN-LAST:event_creerficheA

    private void loginA(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginA
        try {
            conn = mysql.Connect();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        String nom = pseudoField.getText();
        String mot = passField.getText();
//        Connection conn = null;
//        try {
//            conn = mysql.Connect();
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }
        Statement stmt;
        ResultSet res = null;
        List<String> Lpseudo = new ArrayList<String>();
        List<String> Lpass = new ArrayList<String>();
        //obsolète :        List<String> Lrole = new ArrayList<String>();
        List<Boolean> Lconsult = new ArrayList<Boolean>();
        List<Boolean> Lindex = new ArrayList<Boolean>();
        List<Boolean> Lvalid = new ArrayList<Boolean>();
        List<Boolean> Ladmin = new ArrayList<Boolean>();
        List<String> Linitiale = new ArrayList<String>();
        try {
            stmt = conn.createStatement();
            res = stmt.executeQuery("SELECT * FROM membre");
            while (res.next()) {
                Lpseudo.add(res.getString("pseudo"));
                Lpass.add(res.getString("pass"));
                //obsolete  //Lrole.add(res.getString("role"));
                Lconsult.add(res.getBoolean("consult"));
                Lindex.add(res.getBoolean("indexation"));
                Lvalid.add(res.getBoolean("validation"));
                Ladmin.add(res.getBoolean("administ"));
                 Linitiale.add(res.getString("initiale"));
            }
            res.close();
            stmt.close();
//            conn.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        int no = 0;
        while (no < Lpseudo.size()) {
            if ((Lpseudo.get(no).equals(nom)) && (Lpass.get(no).equals(mot))) {
                if ((Lconsult.get(no)) && (Lvalid.get(no)) && (Lindex.get(no))) {
                    pseudoField.setBackground(Color.green);
                    passField.setBackground(Color.green);
                    login = true; // login "normal"
                    if (Ladmin.get(no)) {
                        // login admin
                        loginadmin = true;
                        adminButton.setEnabled(true);
                        logoutButton.setEnabled(true);
                       initialeLogin = Linitiale.get(no);
                    }
                    creerficheButton.setEnabled(true);
                    logoutButton.setEnabled(true);
                }
                break;
            } else {
                no++;
            }
            login = false; //pas de login
            pseudoField.setBackground(Color.red);
            passField.setBackground(Color.red);
        }
}//GEN-LAST:event_loginA
    public void logout() {
        logoutA(null);
    }
    private void logoutA(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logoutA
        login = false;
        pseudoField.setText("");
        passField.setText("");
        pseudoField.setBackground(new Color(255, 255, 204));
        passField.setBackground(new Color(255, 255, 204));
        adminButton.setEnabled(false);
        creerficheButton.setEnabled(false);
        if (this.commandescreateJFrame != null) {
            commandescreateJFrame.dispose();
            commandescreateOpen = 0;
        }
        if (this.recherchesconsultJFrame != null) {
            recherchesconsultJFrame.dispose();
            rechercheconsult = 0;
        }
        if (this.archivageJFrame != null) {
            archivageJFrame.dispose();
            archivageOpen = 0;
        }
        try {
            conn.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        consultButton.setEnabled(true);
        logoutButton.setEnabled(false);

}//GEN-LAST:event_logoutA

    private void quitterAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitterAction
        //TODO sauvegardes et confirmations
        System.exit(0);
    }//GEN-LAST:event_quitterAction

    public static void main(String args[]) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                CEHA main = null;
                try {
                    main = new CEHA();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                main.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton adminButton;
    private javax.swing.JButton consultButton;
    private javax.swing.JButton creerficheButton;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JMenu fichierM;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private java.util.List<ceha.Fiche> list;
    private javax.swing.JButton loginButton;
    private javax.swing.JPanel loginPanel;
    private javax.swing.JButton logoutButton;
    private javax.swing.JPanel mainpanel;
    private javax.swing.JPanel panelB;
    private javax.swing.JPasswordField passField;
    private javax.swing.JLabel passLabel;
    private javax.swing.JTextField pseudoField;
    private javax.swing.JLabel pseudoLabel;
    private javax.persistence.Query query;
    // End of variables declaration//GEN-END:variables
}
